home *** CD-ROM | disk | FTP | other *** search
- Path: armltd.co.uk!dseal
- From: dseal@armltd.co.uk (David Seal)
- Newsgroups: comp.arch.arithmetic,comp.lang.c,comp.lang.c++
- Subject: Re: Access carry flag from C
- Date: 20 Feb 1996 17:46:51 GMT
- Organization: Advanced RISC Machines Ltd
- Message-ID: <4gd1eb$nti@doc.armltd.co.uk>
- References: <Dn1C9z.DGv.0.net@indra.com> <1996Feb1922.17.19.879@koobera.math.uic.edu> <31298D20.41C6@bazis.nl> <ARTHUR.96Feb20143404@gold.Smallworld.co.uk>
- NNTP-Posting-Host: sun11.armltd.co.uk
-
- arthur@Smallworld.co.uk (Arthur Chance) writes:
-
- >In article <31298D20.41C6@bazis.nl> Franz Korntner <fkorntne@bazis.nl> writes:
- >> j+k will overflow when the result exceeds MAXINT
- >>
- >> Thus: "if (j+k > MAXINT) overflow();" but the operation is undefined
- >> if the result overflows, so the expression needs rewriting to make sure
- >> this doesn't happen. The result is then "if (j>MAXINT-k) overflow();".
- >
- >As we must be talking about signed ints, because unsigned can't cause
- >undefined behaviour by overflow, if k < 0, then MAXINT-k overflows.
- >
- >Basically, the C *standard* is useless on things like signed overflow
-
- Not entirely, but you have to be very careful to "guard" everything
- you do. E.g. in the above case, you can precede the "(j>MAXINT-k)"
- test with "(k>=0) &&" to ensure that you get a false result when k is
- negative.
-
- I believe the following is a safe test for signed overflow of j+k in
- C (assuming <limits.h> has been included):
-
- ((k>=0) ? (j > INT_MAX-k) : (j < INT_MIN-k))
-
- (with extra brackets around each "j" and each "k" if you use it as a
- macro expansion, of course). The idea is that:
-
- * If k is non-negative, then j+k >= j as mathematical numbers. Since j
- is in the signed range, this means that j+k can only overflow
- positively. So we want to know whether j+k > INT_MAX, which can be
- transformed into j > INT_MAX-k, and we know that INT_MAX-k won't
- overflow if k is non-negative.
-
- * If k is negative, then j+k < j as mathematical numbers. Since j
- is in the signed range, this means that j+k can only overflow
- negatively. So we want to know whether j+k < INT_MIN, which can be
- transformed into j < INT_MIN-k, and we know that INT_MIN-k won't
- overflow if k is negative.
-
- Fortunately, as others have pointed out, the test for unsigned
- overflow (which is usually what the C flag is about) is much simpler,
- due to C defining the properties of unsigned arithmetic more fully.
- The usual test is to compare the result of the addition with either of
- the operands; you've got overflow if and only if the result is less
- than the operand.
-
- David Seal
- dseal@armltd.co.uk
-